﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
	m_UpdateTimer.start(1000);
	connect(&m_UpdateTimer, &QTimer::timeout, this, &MainWindow::slot_DealUpdateTimer);
	connect(&m_SerialPort, &QSerialPort::readyRead, this, [=]
	{
		QByteArray arry = m_SerialPort.readAll();
		if (ui->radioButton_SerialRecvHEX->isChecked())
		{
			arry = arry.toHex(' ').toUpper();
		}
		ui->plainTextEdit_SerialportDataLog->appendPlainText(arry);
	});
	connect(&m_UdpSocket, &QUdpSocket::readyRead, this, [=]
	{
		QNetworkDatagram NetworkDatagram = m_UdpSocket.receiveDatagram();
		QByteArray arry = NetworkDatagram.data();
		if (ui->radioButton_NetRecvHEX->isChecked())
		{
			arry = arry.toHex(' ').toUpper();
		}
		ui->plainTextEdit_NetDataLog->appendPlainText(arry);
	});
// 	connect(&m_TcpServer, &QTcpServer::readyRead, this, [=]
// 	{
// 		ui->plainTextEdit_SerialportDataLog->appendPlainText(m_SerialPort.readAll());
// 	});
	connect(&m_TcpSocket, &QTcpSocket::readyRead, this, [=]
	{
		ui->plainTextEdit_NetDataLog->appendPlainText(m_TcpSocket.readAll());
	});
}

MainWindow::~MainWindow()
{
	CloseAllNet();
    delete ui;
}

void MainWindow::on_pushButton_OpenSerialPort_clicked()
{
	bool bOpenResult = false;
	if (!m_SerialPort.isOpen())
	{
		m_SerialPort.setPortName(ui->comboBox_PortName->currentText());
		m_SerialPort.setBaudRate(ui->comboBox_BaudRate->currentText().toInt());
		m_SerialPort.setDataBits(static_cast<QSerialPort::DataBits>(ui->comboBox_DataBits->currentText().toInt()));
		m_SerialPort.setStopBits(static_cast<QSerialPort::StopBits>(ui->comboBox_StopBits->currentText().toInt()));
		m_SerialPort.setParity(static_cast<QSerialPort::Parity>(ui->comboBox_Parity->currentText().toInt()));
		m_SerialPort.setFlowControl(static_cast<QSerialPort::FlowControl>(ui->comboBox_FlowControl->currentText().toInt()));
		bOpenResult = m_SerialPort.open(QIODevice::ReadWrite);
	}
	else
	{
		bOpenResult = false;
		m_SerialPort.close();
	}
	ui->pushButton_OpenSerialPort->setText(bOpenResult ? tr("关闭") : tr("打开"));
	ui->comboBox_PortName->setEnabled(!bOpenResult);
	ui->comboBox_BaudRate->setEnabled(!bOpenResult);
	ui->comboBox_DataBits->setEnabled(!bOpenResult);
	ui->comboBox_StopBits->setEnabled(!bOpenResult);
	ui->comboBox_Parity->setEnabled(!bOpenResult);
	ui->comboBox_FlowControl->setEnabled(!bOpenResult);
}

void MainWindow::on_pushButton_SerialportSend_clicked()
{
	QByteArray arry = ui->plainTextEdit_SerialportDataSend->toPlainText().toLatin1();
	if (ui->radioButton_SerialSendHEX->isChecked())
	{
		arry = QByteArray::fromHex(arry);
	}
	if (m_SerialPort.isOpen())
		m_SerialPort.write(arry);
}

void MainWindow::on_pushButton_NetSend_clicked()
{
	QByteArray arry = ui->plainTextEdit_NetDataSend->toPlainText().toLatin1();
	if (ui->radioButton_NetSendHEX->isChecked())
	{
		arry = QByteArray::fromHex(arry);
	}
	QString strDesIP = ui->lineEdit_DesAdress->text();
	unsigned short usDesPort = ui->spinBox_DesPort->value();
	QString strHost = ui->lineEdit_DesAdress->text();
	QHostAddress DesHostAddress(strHost);
	if (DesHostAddress.isNull())
	{
		QMessageBox::warning(this, "网络调试助手", "目的IP错误\n" + strHost);
		return;
	}
	switch (ui->comboBox_NetAgreement->currentIndex())
	{
		case 0:
		{
//			if (m_UdpSocket.isValid() && m_UdpSocket.isWritable())
			{
				m_UdpSocket.writeDatagram(arry, DesHostAddress, usDesPort);
			}
		}
		break;
		case 1:
		{
// 			if (m_TcpServer.isListening())
// 			{
// 				m_TcpServer.con
// 			}
		}
		break;
		case 2:
		{
			if (m_TcpSocket.isValid()&& m_TcpSocket.isWritable())
			{
				m_TcpSocket.write(arry);
			}
		}
		break;
		default:
		{
			QMessageBox::warning(this, "网络调试助手", "不支持的协议");
		}
		break;
	}
}

void MainWindow::on_pushButton_OpenNet_clicked()
{
	bool bOpenResult = false;
	CloseAllNet();
	QString strLocalAdress = ui->comboBox_LocalAdress->currentText();
	QHostAddress LocalHostAddress(strLocalAdress);
	if (strLocalAdress.contains("绑定所有网卡"))
	{
		LocalHostAddress = QHostAddress::AnyIPv4;
	}
	unsigned short usLocalPort = ui->spinBox_LocalPort->value();
	QString strDesIP = ui->lineEdit_DesAdress->text();
	unsigned short usDesPort = ui->spinBox_DesPort->value();
	QString strHost = ui->lineEdit_DesAdress->text();
	QHostAddress DesHostAddress(strHost);
	if (ui->pushButton_OpenNet->text().contains("打开"))
	{
		switch (ui->comboBox_NetAgreement->currentIndex())
		{
			case 0:
			{
				bOpenResult = m_UdpSocket.bind(LocalHostAddress, usLocalPort);
			}
			break;
			case 1:
			{
				bOpenResult = m_TcpServer.listen(LocalHostAddress, usLocalPort);
			}
			break;
			case 2:
			{
				m_TcpSocket.connectToHost(DesHostAddress, usDesPort);
				bOpenResult = m_TcpSocket.waitForConnected();
//				bOpenResult = m_TcpSocket.bind(LocalHostAddress, usLocalPort);
			}
			break;
			default:
			{
				QMessageBox::warning(this, "网络调试助手", "不支持的协议");
			}
			break;
		}
	}
	ui->pushButton_OpenNet->setText(bOpenResult ? tr("关闭") : tr("打开"));
	ui->comboBox_NetAgreement->setEnabled(!bOpenResult);
	ui->comboBox_LocalAdress->setEnabled(!bOpenResult);
	ui->spinBox_LocalPort->setEnabled(!bOpenResult);
	ui->lineEdit_DesAdress->setEnabled(!bOpenResult);
	ui->spinBox_DesPort->setEnabled(!bOpenResult);
}

void MainWindow::CloseAllNet()
{
	if (m_TcpServer.isListening())
	{
		m_TcpServer.close();
	}
	if (m_UdpSocket.isValid())
	{
		m_UdpSocket.close();
		m_UdpSocket.waitForDisconnected();
	}
	if (m_TcpSocket.isValid())
	{
		m_TcpSocket.close();
		m_TcpSocket.waitForDisconnected();
	}
}

void MainWindow::slot_DealUpdateTimer()
{
	static QStringList PerSerialPortList;
	QList<QSerialPortInfo> CuSerialPortInfo = QSerialPortInfo::availablePorts();
	const unsigned char ucCount = CuSerialPortInfo.count();
	QStringList CurSerialPortList;
	for (unsigned char ucLen = 0; ucLen < ucCount; ucLen++)
	{
		CurSerialPortList.push_back(CuSerialPortInfo.at(ucLen).portName());
	}
	if (CurSerialPortList != PerSerialPortList && ui->comboBox_PortName->isEnabled())
	{
		ui->comboBox_PortName->clear();
		ui->comboBox_PortName->addItems(CurSerialPortList);
		PerSerialPortList = CurSerialPortList;
	}
	static QList<QHostAddress> PeripAddressesList;
	QList<QHostAddress> CuripAddressesList = QNetworkInterface::allAddresses(); // 获取所有ip
	if (CuripAddressesList != PeripAddressesList && ui->comboBox_LocalAdress->isEnabled())
	{
		ui->comboBox_LocalAdress->clear();
		ui->comboBox_LocalAdress->addItem("绑定所有网卡");
		for (int i = 0; i < CuripAddressesList.size(); ++i)
		{
			QHostAddress ipAddr = CuripAddressesList.at(i);
			if (ipAddr.protocol() == QAbstractSocket::IPv4Protocol)// 筛选出ipv4
			{
				ui->comboBox_LocalAdress->addItem(CuripAddressesList.at(i).toString());
			}
		}
		PeripAddressesList = CuripAddressesList;
	}
}
